package com.luli.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.luli.Utils.RedisUtils;
import com.luli.dao.UsersDao;
import com.luli.entity.UserData.UpdateUserParam;
import com.luli.entity.Users;
import com.luli.entity.login.RegisterUser;
import com.luli.entity.response.ResponseMsg;
import com.luli.service.RedisUsersService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import redis.clients.jedis.Jedis;

import java.util.List;

import static com.luli.Utils.ResponseMsgUtil.getSuccessMsg;

/**
 * 陆离
 * 2022/5/5 13:41:36
 */
@Service
public class RedisUsersServiceImpl implements RedisUsersService {
    @Autowired
    private UsersDao usersDao;

    @Autowired
    private RedisUtils redisUtil;
    @Override
    public List<Users> getUsers(String userName) {
        List<Users> users = usersDao.findByAccount(userName);
        Jedis jedis = new Jedis("127.0.0.1",6379);
        String ping = jedis.ping();
        if (!ping.equals("PONG")){
            return null;
        }
        JSONArray objects = JSONObject.parseArray(JSON.toJSONString(users));
        String data = objects.toJSONString();
        jedis.lpush(userName, data);
        return users;
    }


    @Override
    public ResponseMsg<?> addData(RegisterUser listData) {
        int userNum=usersDao.addDataUser(listData);
        if (userNum == 1){
            Jedis jedis = new Jedis("127.0.0.1",6379);
            if (!"PONG".equals(jedis.ping())){
                return null;
            }
            jedis.lpush("UserData", JSON.toJSONString(listData));
        }
        return getSuccessMsg(null, "新增成功！", null);
    }

    @Override
    public ResponseMsg<?> updateData(UpdateUserParam listData) {
        int userNum = usersDao.updateUser(listData);
        if (userNum == 1){
            Jedis jedis = new Jedis("127.0.0.1",6379);
            if (!"PONG".equals(jedis.ping())){
                return null;
            }
            redisUtil.lUpdateIndex("UserData",0L,listData);
        }
        return getSuccessMsg(null, "修改成功！", null);
    }


    @Override
    public ResponseMsg<?> delData(String account) {
        int userNum = usersDao.delUserById(account);
        if (userNum == 1){
            Jedis jedis = new Jedis("127.0.0.1",6379);
            if (!"PONG".equals(jedis.ping())){
                return null;
            }
            redisUtil.lRemove("UserData",0L,account);
        }
        return getSuccessMsg(null, "删除成功！", null);
    }
}
